import {
  getToken
} from '@/utils/auth'
import {
  dynamicRoutes
} from '@/router/index'
import {
  getMenus
} from '@/api/user'

const getDefaultState = () => {
  return {
    token: getToken(),
    menuList: []
  }
}


const state = getDefaultState()

const mutations = {
  SET_MENUS: (state, menus) => {
    state.menuList = menus
  }
}

// 动态菜单还是定义在前端，后台只会返回有权限的菜单列表，通过遍历服务端的菜单数据，没有的将对于菜单进行隐藏
// 这样的好处是服务端无需返回前端菜单相关结构，并且菜单显示又可以通过服务端来控制，进行菜单的动态控制
export function generaMenu(routes, srvMenus) {
  for (let i = 0; i < routes.length; i++) {
    const routeItem = routes[i]
    var showItem = false
    for (let j = 0; j < srvMenus.length; j++) {
      const srvItem = srvMenus[j]
      // 前后端数据通过 srvName 属性来匹配
      if (routeItem.srvName !== undefined && routeItem.srvName === srvItem.srvName && srvItem.show === true) {
        showItem = true
        routes[i]['hidden'] = false
        break
      }
    }
    if (showItem === false) {
      routes[i]['hidden'] = true
    }
    if (routeItem['children'] !== undefined && routeItem['children'].length > 0) {
      generaMenu(routes[i]['children'], srvMenus)
    }
  }
}

const filterName = (data, names) => {
  data.forEach((node => {
    names.push(node.srvName);
    if (node.children && node.children.length) {
      filterName(node.children, names);
    }
  }));
};

const zip = ([x, ...xs], [y, ...ys]) => {
  if (x === undefined || y === undefined) return [];
  return [
    [x, y], ...zip(xs, ys)
  ];
};

const actions = {
  getMenus({
    commit
  }) {
    let data = {
      userId: localStorage.getItem('ID'),
      last_ip: sessionStorage.getItem("Ip")
    }
    return new Promise((resolve, reject) => {
      getMenus(data).then(response => {
        commit('user/SET_AV_TIME', response.data[0].av_time, {root: true})
        var pushRouter = JSON.parse(JSON.stringify(dynamicRoutes))
        let names = [];
        let data = JSON.parse(JSON.stringify(pushRouter))
        filterName(data, names) //获取当前所有的路由路径
        let arr = response.data[0].rules //后台返回用户的数组菜单,1显示，0隐藏
        arr = arr.split('')
        arr.forEach((item, index, arrs) => { //转为boolean
          return arrs[index] = Number(item) && Boolean(item)
        })
        let s = zip(names, arr).map(([srvName, show]) => ({
          srvName,
          show
        })); //把菜单和所有路径合并
        generaMenu(pushRouter, s) //传递处理
        commit('SET_MENUS', pushRouter)
        resolve(pushRouter)
      }).catch(err => {
        reject(err.msg)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
